Ext.namespace("Dudley");
Ext.namespace("Dudley.lims");

Dudley.lims.Chemical = function() {

    var myChemicalData = [];
    var chemicalForm = {};
    var chemicalPanel = {};
    var chemicalHash = null;
    var chemicalCount = null;
    var chemicalMaxNum = null;
    var chemicalStore = [];
    var chemicalLoaded = false;

    function initChemicalStore(failedCb, callback) {
        loadChemicalSearchResult(0, null, callback);
    }

    function loadChemicalSearchResult(index, searchResultJSON, callback) {
        chemicalStore = loadSolrSearchResult("Chemical", getChemicalPagingColumns(), chemicalSolrTranslator, index, searchResultJSON);
        chemicalStore.load({params:{start:0, limit:10}}, callback());		     
    }

    function goSearch(index, chemicalSearchInput, chemicalSearchOption) {
        if (chemicalSearchInput == '') {
                chemicalSearchInput = 'CHEM';
        }
        chemicalSearchInput = checkWildcard(chemicalSearchInput);        
        var searchUrl = getSolrSearchUrl(getLuceneTerm("chemFields",chemicalSearchInput), 1000, "chemKey,chemName,chemLocation,chemReorder,chemAlias,chemKeywords,chemComments");
        var searchWin = getSearchLoadingWindow("chemical-");        
        searchWin.on("show", function () {
            var sb = Ext.getCmp("chemical-search-statusbar");
            sb.showBusy();
        });
        searchWin.show();
        Ext.Ajax.request({
            url: searchUrl,
            method: "GET",
            success: function(response) {
                var searchResultObj = Ext.util.JSON.decode(response.responseText);
                console.log("Result count:" + searchResultObj.response.numFound);
                myChemicalData = [];
                loadChemicalSearchResult(index, searchResultObj.response, function() {
                    Ext.getDom("sample-search-result-list").innerHTML = "";
                    Ext.getDom("yo-form").innerHTML = "";
                    searchWin.close();
                    renderChemicalSearchResult();
                });
            },
            failure: function() {
                eventManager.fireStatusMessageEvent({ text: "Search Results failed for url:" + searchUrl, level: "error" });
            }
        });
    }

    function loadChemicalPanel() {
       var chemicalSearchForm = getSearchForm("chemicalSearchButtonId", "chemicalSearchInputId", null);
       Ext.getCmp("chemicalSearchButtonId").addListener("click", function(){
			goSearch(0, Ext.getCmp("chemicalSearchInputId").getValue(), "chemFields");		
		});		
        var tbarButtons = [
            {
                id: 'showChemicalSearchResultsId',
                name: 'showChemicalSearchResults',
                disabled: true,
                text: '<--Search Results',
                icon: "images/back-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("yo-form").innerHTML = "";
                            renderChemicalSearchResult();
                        }
                }
            },
            {
                id: 'searchAllChemicalId',
                name: 'searchAllChemical',
                disabled: false,
                text: 'View All Records',
                icon: "images/search-blue.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("yo-form").innerHTML = "";
                            goSearch(0, '*', 'All');
                        }
                }
            },
            {
                id: 'createNewChemicalId',
                name: 'createNewChemical',
                text: 'Create New Chemical',
                icon: "images/add-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Dudley.lims.Chemical.loadNewChemical();
                        }
                }
            }
        ];
        chemicalPanel = new Ext.Panel({
            id: "chemicalPanelId",
            autoHeight: true,
            border: true,
            renderTo: "yad-panel",
            title: "Chemical",
            header: false,
            tbar: tbarButtons,
            items: chemicalSearchForm
        });
        chemicalPanel.on("activate", function () {
            Ext.getDom("yo-panel").innerHTML = "";
            Ext.getDom("yo-form").innerHTML = "";
            Ext.getDom("sample-search-result-list").innerHTML = "";
            if (!chemicalLoaded) {
                chemicalLoaded = true;
                goSearch(0, 'CHEM', 'chemFields');
            }else{
            	renderChemicalSearchResult();
            }
        });
    }

    function postChemicalStrain(createNew) {
        var chemicalJson = new Object();
        var chemicalKey = Ext.getCmp("chemicalKeyId").getValue();
        chemicalJson["chemKey"] = chemicalKey;
        chemicalJson["chemName"] = Ext.getCmp("chemicalNameId").getValue();
        chemicalJson["chemAlias"] = Ext.getCmp("chemicalAliasId").getValue();
        chemicalJson["chemLocation"] = Ext.getCmp("chemicalLocationId").getValue();
        chemicalJson["chemKeywords"] = Ext.getCmp("chemicalKeywordId").getValue();
        chemicalJson["chemReorder"] = Ext.getCmp("chemicalReorderId").getValue();
        chemicalJson["chemComments"] = Ext.getCmp("chemicalCommentsId").getValue();
        var chemicalCallback = function() {
        	limsadmin_obj["limsadminChemCount"] = chemicalCount; 
            limsadmin_obj['limsadminChemMaxNum'] = chemicalMaxNum;
			postSolrUpdates(limsadmin_obj, function(){            
                eventManager.fireStatusMessageEvent({ text: "New Chemical Strain Added Successfully", level: "info" });
                Ext.Msg.alert('Info', "New Chemical " + chemicalKey + ' Added Successfully');
                Ext.getDom("yo-form").innerHTML = "";
                goSearch(0, chemicalKey, "chemFields");
            });
        };
        if (!createNew) {
            chemicalCallback = function() {
                Ext.Msg.alert('Info', chemicalKey + ' Updated Successfully');
                var searchResultsButton = Ext.getCmp("showChemicalSearchResultsId");
                searchResultsButton.disable();
            };
        }
        postSolrUpdates(chemicalJson, chemicalCallback);
    }

    function loadCreateChemicalStrain(chemicalHash, callback) {
        var createNew = true;
        var buttons = [
            {
                id: 'createButton',
                name: 'createButton',
                text: 'Create',
                listeners: {click:
                        function() {
                            if (validateCreateUpdateChemical()) {
                                postChemicalStrain(createNew);
                            }
                        }
                }
            }
        ];
        if (chemicalHash != null) {
            if (chemicalHash.genotype != undefined && chemicalHash.genotype == 'Record Deleted') {
                buttons = [];
            } else {
                buttons = [
                    {
                        id: 'updateChemicalButtonId',
                        name: 'updateChemicalButton',
                        text: 'Update',
                        listeners: {click:
                                function() {
                                    if (validateCreateUpdateChemical()) {
                                        postChemicalStrain(!createNew);
                                    }
                                }
                        }
                    },
                    {
                        id: 'deleteChemicalButtonId',
                        name: 'deleteChemicalButton',
                        text: 'Delete',
                        //disabled: true,
                        listeners: {click:
                                function() {
                                    var deleteUrl = "/addama-rest/dudley-sample/path/datasource/Chemical/" + chemicalHash.name + "/annotations/?JSON={deletechemical:true}";
                                    Ext.Msg.confirm('Message', "Please confirm that you want to delete " + chemicalHash.name + "", function(btn) {
                                        if (btn == 'yes') {
                                            Ext.Ajax.request({
                                                url: deleteUrl,
                                                method: "POST",
                                                success: function() {
                                                    Ext.Msg.alert(chemicalHash.name + " deleted, Chemical Strains Reloading...");
                                                    goSearch(0, '*', 'All');
                                                },
                                                failure: function() {
                                                    eventManager.fireStatusMessageEvent({ text: "Delete Failed for " + chemicalHash.name, level: "error" });
                                                }
                                            });
                                        }
                                    });
                                }
                        }
                    }
                ];
            }
        } else {
            chemicalHash = new Object();
            var chemicalMaxInt = parseInt(chemicalMaxNum);
            chemicalMaxInt = chemicalMaxInt + 1;
            var chemicalCountInt = parseInt(chemicalCount);
            chemicalCountInt = chemicalCountInt + 1;
            chemicalCount = chemicalCountInt + "";
            chemicalHash.name = 'CHEM' + chemicalMaxInt;
            chemicalMaxNum = chemicalMaxInt + "";
            if (chemicalHash.comments == null) {
                chemicalHash.comments = "";
            }

        }
        chemicalForm = new Ext.form.FormPanel({
            id: 'chemicalForm',
            method: 'POST',
            autoHeight: true,
            autoScroll: true,
            border: true,
            buttonAlign: 'left',
            buttons: buttons,
            items: [
                new Ext.form.FieldSet({
                    autoHeight: true,
                    border: false,
                    items: [
                        new Ext.form.TextField({
                            id: "chemicalKeyId",
                            fieldLabel: "Key",
                            name: "chemicalKey",
                            value: chemicalHash.name,
                            width: 500,
                            readOnly: true,
                            allowBlank: false
                        }),
                        new Ext.form.TextField({
                            id: "chemicalNameId",
                            fieldLabel: "Name",
                            name: "chemicalName",
                            value: chemicalHash.chemicalName,
                            width: 500,
                            allowBlank: false
                        }),
                        new Ext.form.TextField({
                            id: "chemicalAliasId",
                            fieldLabel: "Alias",
                            value: chemicalHash.alias,
                            width: 500,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Shorter version/nickname of chemical'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "chemicalKeywordId",
                            fieldLabel: "Keywords",
                            value: chemicalHash.keyword,
                            width: 500,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Enter category of the chemical, ie amino acid, antibody, detergent, stain, ... etc'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "chemicalLocationId",
                            fieldLabel: "Location",
                            name: "chemicalLocation",
                            value: chemicalHash.location,
                            width: 500,
                            allowBlank: false
                        }),
                        new Ext.form.TextField({
                            id: "chemicalReorderId",
                            fieldLabel: "Reorder",
                            name: "chemicalReorder",
                            value: chemicalHash.reorderKey,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Company, catalog number, reorder number, qty'
                                    });
                                }
                            }
                        }),
                        {
                            xtype:'htmleditor',
                            id:'chemicalCommentsId',
                            value: chemicalHash.comments,
                            fieldLabel:'Comments ' + '<br><i><font size=-2>Relevant information, such as safety info, about the chemical not covered in other fields</font></i>',
                            height:100,
                            labelSeparator: '',
                            anchor:'98%',
                            listeners: {
                                activate: function(e) {
                                    if (chemicalHash.comments == undefined || chemicalHash.comments == "") {
                                        e.execCmd('delete');
                                    }
                                }
                            }
                        }
                    ]
                })
            ]
        });
        callback();

    }

    // render the grid to the specified div in the page
    function renderChemicalSearchResult() {
        var searchResultsButton = Ext.getCmp("showChemicalSearchResultsId");
        if (searchResultsButton != null || searchResultsButton != undefined) {
            searchResultsButton.disable();
        }
        var mytbar = [
            {
                id: 'chem2CSVId',
                text: 'Export2CSV',
                icon: "images/check-green.png",
                cls:'x-btn-text-icon',
                tooltip: 'Export search results to csv',
                listeners: {click:
                        function() {
                            Dudley.lims.Chemical.toCSV();
                        }
                }
            }
        ];

        var searchResultsGrid = new Ext.grid.GridPanel({
            id: "chemicalSearchResultsId",
            store: chemicalStore,
            columns: getChemicalSearchColumnHeaders(),
            stripeRows: true,
            autoHeight: true,
            width: 800,
            title: 'Chemical',
            renderTo: "sample-search-result-list",
            bbar: new Ext.PagingToolbar({
                pageSize: 10,
                store: chemicalStore,
                displayInfo: true,
                displayMsg: 'Displaying strains {0} - {1} of {2}',
                emptyMsg: "No strains to display"
            }),
            tbar: mytbar
        });
        searchResultsGrid.on("celldblclick", function (g, ri, ci, e) {
            var searchResultsButton = Ext.getCmp("showChemicalSearchResultsId");
            searchResultsButton.enable();
            chemicalHash = new Object();
            populateChemicalJson(chemicalHash, g);
            loadCreateChemicalStrain(chemicalHash, function() {
            	chemicalFormRender();
            });                          
        });
    }

    function chemicalFormRender() {
        Dudley.lims.samplemgr.getHousingPanel().activate(chemicalPanel);
        Ext.getDom("sample-search-result-list").innerHTML = "";
        Ext.getDom("yo-form").innerHTML = "";
        chemicalForm.render("yo-form");
    }
    
    function setChemAdmin(jsonObj){
    	limsadmin_obj =  jsonObj;
    	chemicalCount = jsonObj.limsadminChemCount;
                        chemicalMaxNum = jsonObj.limsadminChemMaxNum;                       
                        chemicalHash = null;
                        Ext.getCmp("showChemicalSearchResultsId").enable();
                        loadCreateChemicalStrain(chemicalHash, function() {
                            Ext.getDom("sample-search-result-list").innerHTML = "";
                            Ext.getDom("yo-form").innerHTML = "";
                            chemicalForm.render("yo-form");
                        });
     }                   

    // public
    return {
        initChemical: function(failedCB) {
            initChemicalStore(failedCB, function() {
                eventManager.fireStatusMessageEvent({ text: "Finishing init Chemical Store", level: "info" });
                //renderChemicalSearchResult();
            });
        },

        getChemicalPanel: function() {
            loadChemicalPanel();
            return chemicalPanel;
        },

        getChemicalStore: function() {
            return chemicalStore;
        },

        loadNewChemical: function() {
            Ext.getDom("yo-form").innerHTML = "";
            
            getSolrLimsAdmin(setChemAdmin);                      
        },
        loadSearchResult: function() {
            Ext.getDom("sample-search-result-list").innerHTML = "";
            renderChemicalSearchResult();
        },
        toCSV: function() {
            var csvText = "chemKey,chemName,chemLocation,chemReorder,chemAlias,chemKeywords,chemComments" + breakDelimiter;
            myChemicalData.sort(function(a, b) {
                return a[0] - b[0];
            });
            for (var c = 0; c < myChemicalData.length; c++) {
                var cArray = myChemicalData[c];
                for (var ci = 0; ci < cArray.length; ci++) {
                    if (cArray[ci] == undefined || cArray[ci] == null) {
                        cArray[ci] = "";
                    }
                    cArray[ci] = cArray[ci] + "";
                    cArray[ci] = cArray[ci].replace(/'/g, "");
                    cArray[ci] = '"' + cArray[ci] + '"';
                }
                csvText = csvText + "" + cArray[1] + "," + cArray[2] + "," + cArray[3] + "," + cArray[4] + "," + cArray[5]  + "," + cArray[6] + "," + cArray[7] + breakDelimiter;
            }
            export2Csv("ChemicalSearchedResults.csv", csvText, "chemical2Csv");
        } ,
        setArrayData: function(data) {
                    myChemicalData = data;
         }
    };
}();
